import { Component, EventEmitter, OnInit, Output, ViewChild } from "@angular/core";
import { FormBuilder, FormControl, FormGroup, NgForm, Validators } from "@angular/forms";
import { UserService } from "../../../pms/user-list/user.service";
import { DeviceService } from "../../device-list/device.service";
import { DeviceInspectionPlanService } from "../device-inspection-plan.service";
import { NzMessageService } from "ng-zorro-antd/message";
import { NzTreeNode } from "ng-zorro-antd/tree";
import { DeviceInspectionTemplateService } from "../../device-inspection-template/device-inspection-template.service";
import { DictionaryService } from "../../../sys/dictionary/dictionary.service";

@Component({
  selector: "app-device-inspection-plan-edit",
  templateUrl: "./device-inspection-plan-edit.component.html",
  styles: []
})
export class DeviceInspectionPlanEditComponent implements OnInit {


  constructor(private formBuilder: FormBuilder,
              private msgSrv: NzMessageService,
              private deviceInspectionPlanSrv: DeviceInspectionPlanService,
              private deviceInspectionTemplateService: DeviceInspectionTemplateService,
              private userSrv: UserService,
              private deviceSrv: DeviceService,
              private dictionaryService: DictionaryService,
  ) {
  }

  nzLoading = false;

  @Output() voted = new EventEmitter();

  @ViewChild('dataForm', { static: false }) validateForm: NgForm;

  // 检验信息数据
  formData: any = {};
  // 是否编辑
  isUpdate = false;
  // 人员
  users = [];
  // 设备
  devices = [];
  // 模板
  templates = [];
  // 检验类型,从字典加载
  inspectionType = [];

  dateRange = [];
  dateFormat = "yyyy-MM-dd";
  visible = false;
  isView = false;

  value?: [];

  // 点检项目数据
  listOfData: any[] = [];

  open(): void {
    this.formData = {};
    this.listOfData = [];
    this.validateForm.reset();
    this.visible = true;
    this.isUpdate = false;
  }

  edit(param) {
    this.visible = true;
    this.isUpdate = true;
    this.value = param?.parent?.id;

    if (param) {
      this.formData = param;
      this.dateRange = [param.planStartTime,param.planEndTime];
      this.listOfData = param['deviceInspectionPlanItemList'];
    } else {
      this.validateForm.reset();
    }
  }

  close(): void {
    this.visible = false;
  }

  // 加载明细数据
  loadItemData(planId){
    this.deviceInspectionPlanSrv.planItems(planId).subscribe(res => {

      if(res.code === 1){
        this.listOfData = res.data;
      }

    })

  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    this.nzLoading = true;

    this.formData['planStartTime'] =  this.dateRange[0];
    this.formData['planEndTime'] =  this.dateRange[1];

    this.formData['deviceInspectionPlanItemList'] = this.listOfData;

    this.deviceInspectionPlanSrv.update(this.formData).subscribe((res) => {

      this.nzLoading = false;

      if (res.code === 1) {
        this.msgSrv.success("保存完成");
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  loadUserDate() {
    this.userSrv.getAll().subscribe((res) => {
      if (res.code === 1) {
        this.users = res.data;
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  loadDeviceDate() {
    this.deviceSrv.getAll().subscribe((res) => {
      if (res.code === 1) {
        this.devices = res.data;
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }


  loadTemplates() {
    this.deviceInspectionTemplateService.getAll().subscribe((res) => {
      if (res.code === 1) {
        this.templates = res.data;
      } else {
        this.msgSrv.error(res.message);
      }
    });
  }

  ngOnInit(): void {
    // 加载人员数据
    this.loadUserDate();
    // 加载设备数据
    this.loadDeviceDate();
    // 加载模板数据
    this.loadTemplates();
    // 加载字典,设备检验类型
    this.loadDict("device_inspection_type");


  }

  // 加载字典数据
  loadDict(dictCode) {
    this.dictionaryService.getDictItem(dictCode).subscribe(res => {
      this.inspectionType = res.data;
    });
  }

  nzDisplayWith(node: NzTreeNode) {
    return node.title;
  }

  addOneRows() {
    this.listOfData.push({});
    this.listOfData = [...this.listOfData];
  }

  delTable() {
    if (this.listOfData.some(item => {
      return item.checked;
    })) {
      for (let i = this.listOfData.length - 1; i >= 0; i--) {
        if (this.listOfData[i]['checked']) {
          let key = this.listOfData[i]['id'];
          this.listOfData.splice(i, 1);
          let temp = JSON.parse(localStorage.getItem('inspectionToTemplate'));
          if (temp && temp['id'] === key) {
            localStorage.removeItem('inspectionToTemplate');
          }
        }
      }
      this.listOfData = [...this.listOfData];
    }

  }

  checkAllInspectionList(bol) {
    if (bol) {
      this.listOfData.forEach(item => {
        item.checked = true;
      });
      this.listOfData = [...this.listOfData];
    } else {
      this.listOfData.forEach(item => {
        item.checked = false;
      });
      this.listOfData = [...this.listOfData];
    }

  }
}
